import { useState }  from 'react';
import moment from 'moment'
import PropsType from "prop-types";
import { DateRangePicker } from "materialui-daterange-picker";
import { TextField, InputAdornment, IconButton } from '@mui/material';
import EventIcon from '@mui/icons-material/Event';

const DateRangePickCus = ({label, placeholder, onChange, value, minDate, maxDate}) => {
  const [open, setOpen] = useState(false)

  const toggle = () => {
    setOpen(!open);
  }

  const onChangeRangDate = (range) => {
    onChange([moment(range.startDate).format('YYYY-MM-DD'), moment(range.endDate).format('YYYY-MM-DD')])
  }

  return (
    <>
      <DateRangePicker
        open={open}
        toggle={toggle}
        onChange={(range) => onChangeRangDate(range)}
        minDate={minDate}
        maxDate={maxDate}
      />
      <TextField
        value={value && value[0] && value[1] ? `${value[0]} - ${value[1]}` : ''}
        onFocus={() => setOpen(true)}
        variant="filled"
        label={label}
        placeholder={placeholder}
        InputProps={{ endAdornment:
          <InputAdornment position="end">
            <IconButton
              edge="end"
              onClick={() => setOpen(true)}
            >
              <EventIcon/>
            </IconButton>
          </InputAdornment> }}
        />
    </>
  )
}

DateRangePickCus.propTypes = {
  placeholder: PropsType.string,
  label: PropsType.string,
  onChange: PropsType.func.isRequired,
  value: PropsType.oneOfType([PropsType.string, PropsType.array]).isRequired,
  minDate: PropsType.any,
  maxDate: PropsType.any
}

DateRangePickCus.defaultProps = {
  placeholder: '时间范围',
  label: '时间范围',
  minDate: new Date(new Date().getTime() - 10 * 365 * 24 * 60 * 60 * 1000),
  maxDate: new Date()
}

export default DateRangePickCus